

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言上篇文章基本都在讲述如何用好一个对象，那么这篇文章就要讲怎么设计好一个类，让这个类更好的进行逻辑的抽离，更好的进行复用。 所以这篇文章，都是围绕着 类的三大特性  封装 继承 多态  废话不多说，我们直接开始介绍。 封装这里的封装，和我们之前接触的 封装函数 有类似的效果 就是 将一段可复用的代码逻辑封装成一个函数 但显然，类的封装要比函数的封装更加高级。 因为类可以根据不同的对象属性来决定内">
<meta property="og:type" content="article">
<meta property="og:title" content="python面向对象（下）">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2023/03/11/python/base/python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%EF%BC%88%E4%B8%8B%EF%BC%89/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言上篇文章基本都在讲述如何用好一个对象，那么这篇文章就要讲怎么设计好一个类，让这个类更好的进行逻辑的抽离，更好的进行复用。 所以这篇文章，都是围绕着 类的三大特性  封装 继承 多态  废话不多说，我们直接开始介绍。 封装这里的封装，和我们之前接触的 封装函数 有类似的效果 就是 将一段可复用的代码逻辑封装成一个函数 但显然，类的封装要比函数的封装更加高级。 因为类可以根据不同的对象属性来决定内">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-03-11T14:23:42.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.267Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="Python基础">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>python面向对象（下） - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="python面向对象（下）"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-03-11 22:23" pubdate>
          2023年3月11日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          8.6k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">python面向对象（下）</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>上篇文章基本都在讲述如何用好一个对象，那么这篇文章就要讲怎么设计好一个类，让这个类更好的进行逻辑的抽离，更好的进行复用。</p>
<p>所以这篇文章，都是围绕着 <strong>类的三大特性</strong></p>
<ul>
<li>封装</li>
<li>继承</li>
<li>多态</li>
</ul>
<p>废话不多说，我们直接开始介绍。</p>
<h1 id="封装"><a href="#封装" class="headerlink" title="封装"></a>封装</h1><p>这里的封装，和我们之前接触的 <strong>封装函数</strong> 有类似的效果</p>
<p>就是 <strong>将一段可复用的代码逻辑封装成一个函数</strong></p>
<p>但显然，类的封装要比函数的封装更加高级。</p>
<p>因为类可以根据不同的对象属性来决定内部函数的走向。</p>
<p>换而言之，就是你和我都是人，但是我会的东西你不一定会；又或者说你我都会的技能，我也许会比你做得更快更好。</p>
<p>说了这么多，封装其实就是像我们上篇文章学过的一样，就是封装 <strong>属性/方法</strong>，然后根据敏感度来决定要不要把它们变成 <strong>私有属性/方法</strong>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Login</span>():<br>    __userConfig = &#123;<br><br>    &#125;<br><br><span class="hljs-meta">    @classmethod</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">login</span>(<span class="hljs-params">cls, userName, password</span>):<br>        result = <span class="hljs-literal">True</span><br>        <span class="hljs-keyword">if</span> cls.__userConfig.get(userName):  <span class="hljs-comment"># 如果账号存在</span><br>            <span class="hljs-keyword">if</span> password != cls.__userConfig[userName]:  <span class="hljs-comment"># 如果密码一样</span><br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;密码错误&quot;</span>)<br>                result = <span class="hljs-literal">False</span><br>        <span class="hljs-keyword">else</span>:<br>            result = <span class="hljs-literal">False</span><br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;账号不存在&quot;</span>)<br>        <span class="hljs-keyword">return</span> result<br>    <br><span class="hljs-meta">    @classmethod</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">register</span>(<span class="hljs-params">cls, userName, password</span>):<br>        result = <span class="hljs-literal">True</span><br>        <span class="hljs-keyword">if</span> cls.__userConfig.get(userName):  <span class="hljs-comment"># 如果账号存在</span><br>            result = <span class="hljs-literal">False</span><br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;账号已存在，请勿重复登录&quot;</span>)<br>        <span class="hljs-keyword">else</span>:<br>            cls.__userConfig[userName] = password<br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;账号注册成功&quot;</span>)<br>        <span class="hljs-keyword">return</span> result<br></code></pre></td></tr></table></figure>

<h1 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h1><p>继承，和字面意思差不多，就是某一个子类继承了父类。</p>
<p>所以子类可以使用父类 <strong>非私有</strong> 的属性/方法。</p>
<p>可以这么去理解，某某人继承了他父亲的遗产，但是他父亲有某些私密的东西想保留随着他一块离去，所以私密的东西只能他父亲自己看到和使用，即使是他的孩子也不能继承。</p>
<p>所以子类和父类有以下关系：</p>
<p>1、子类可以使用父类的属性及方法（实现代码的重用，相同的代码不需要重复的写）<br>2、子类调用方法，先找自己，然后再去找父类，再找父类的父类，依次类推<br>3、子类不能继承父类及父类的私有属性及方法（注意）<br>4、子类可以重写父类的方法<br>  1）覆盖父类的方法<br>  2）扩展父类方法：执行原来的业务逻辑+扩展功能</p>
<p>我们针对上述关系来进行演示</p>
<h2 id="子类可以使用父类的属性及方法"><a href="#子类可以使用父类的属性及方法" class="headerlink" title="子类可以使用父类的属性及方法"></a>子类可以使用父类的属性及方法</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">eat</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我在吃东西&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">doing</span>(<span class="hljs-params">self</span>):<br>        self.eat()  <span class="hljs-comment"># 实际上调用的还是父类的方法</span><br><br><br>child = Child()<br><br>child.eat()  <span class="hljs-comment"># 调用的父类的方法</span><br><br>child.doing()<br></code></pre></td></tr></table></figure>

<h2 id="子类调用方法，先找自己，然后再去找父类"><a href="#子类调用方法，先找自己，然后再去找父类" class="headerlink" title="子类调用方法，先找自己，然后再去找父类"></a>子类调用方法，先找自己，然后再去找父类</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">eat</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我在吃东西&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">eat</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我有一种新的吃法&quot;</span>)<br><br><br>child = Child()<br><br>child.eat()  <span class="hljs-comment"># 实际上调用的是自己的方法</span><br></code></pre></td></tr></table></figure>

<h2 id="子类不能继承父类及父类的私有属性及方法"><a href="#子类不能继承父类及父类的私有属性及方法" class="headerlink" title="子类不能继承父类及父类的私有属性及方法"></a>子类不能继承父类及父类的私有属性及方法</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br><br>    __attr = <span class="hljs-string">&quot;特殊秘密&quot;</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__info</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;爸爸我啊，有特殊的秘密 <span class="hljs-subst">&#123;self.__attr&#125;</span>&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">self</span>):<br>        self.__info()<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">self</span>):<br>        self.__info()  <span class="hljs-comment"># 无法继承</span><br><br>parent = Parent()<br><br>parent.getInfo()<br><br><br>child = Child()<br><br>child.getInfo()  <span class="hljs-comment"># 报错</span><br></code></pre></td></tr></table></figure>

<h2 id="子类可以重写父类的方法"><a href="#子类可以重写父类的方法" class="headerlink" title="子类可以重写父类的方法"></a>子类可以重写父类的方法</h2><h3 id="覆盖父类的方法"><a href="#覆盖父类的方法" class="headerlink" title="覆盖父类的方法"></a>覆盖父类的方法</h3><p>这个其实在上面的例子 <code>getInfo</code>已经展示过了</p>
<p>就是将相同的函数名在子类中重新编写逻辑，调用时就会先调用子类的函数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我是爸爸&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 相同属性名，重写覆盖</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我是儿子&quot;</span>)<br><br>parent = Parent()<br><br>parent.getInfo()<br><br><br>child = Child()<br><br>child.getInfo() <br></code></pre></td></tr></table></figure>

<h3 id="扩展父类方法"><a href="#扩展父类方法" class="headerlink" title="扩展父类方法"></a>扩展父类方法</h3><p>如果我又想执行父类的方法，又想进行定制化呢？</p>
<p>有两种方式：</p>
<ul>
<li>写一个不同名字的函数，在函数中使用 <code>self.xx()</code></li>
<li>写一个相同名字的函数，在函数中使用 <code>super().xx()</code></li>
</ul>
<p><strong>我们先来看第一种</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">getParentInfo</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我是爸爸&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">getChildInfo</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 不同名字的函数，在其中通过self调用父方法</span><br>        self.getParentInfo()<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我是儿子&quot;</span>)<br><br>parent = Parent()<br><br>parent.getParentInfo()<br><br><br>child = Child()<br><br>child.getChildInfo() <br></code></pre></td></tr></table></figure>

<p><strong>第二种</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我是爸爸&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">self</span>): <br>        <span class="hljs-built_in">super</span>().getInfo()  <span class="hljs-comment"># super() 就是指向父类</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我是儿子&quot;</span>)<br><br>parent = Parent()<br><br>parent.getInfo()<br><br><br>child = Child()<br><br>child.getInfo()<br></code></pre></td></tr></table></figure>

<p>相比第一种，我更推荐使用第二种方式。</p>
<p>原因：</p>
<ul>
<li>这才是继承的特色，很好的进行函数覆盖和拓展，在使用时也能够更好的进行区分</li>
<li>从编码规范来说， <code>super().xx()</code> 比 <code>self.xx()</code> 要更直观, 一下子就能让人知道这里调用的是父类方法.</li>
</ul>
<p>假设我们一个类有很多代码, 其中还会涉及到很多父类调用</p>
<p>可以想象的是, 如果其中没有 <code>super</code> 全都是 <code>self</code> </p>
<p>时间拉长后, 维护起来就十分麻烦.</p>
<h1 id="继承注意点"><a href="#继承注意点" class="headerlink" title="继承注意点"></a>继承注意点</h1><h2 id="self指向"><a href="#self指向" class="headerlink" title="self指向"></a>self指向</h2><p>在我们设计类方法的时候 <code>self</code> 通常是指向本身</p>
<p>但是这个时候如果一个类 <strong>被继承</strong> 了</p>
<p>那么继承这个子类, 在实例化后, 父类的self就是指向子类</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">showName</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(self.name)  <span class="hljs-comment"># 实际上用的是子对象的name</span><br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, name</span>) -&gt; <span class="hljs-literal">None</span>:<br>        <span class="hljs-built_in">super</span>().__init__()<br>        self.name = name<br><br><br>child = Child(<span class="hljs-string">&#x27;muzhou&#x27;</span>)<br><br>child.showName()  <span class="hljs-comment"># 调用的父类的方法</span><br></code></pre></td></tr></table></figure>

<h2 id="类初始化函数init"><a href="#类初始化函数init" class="headerlink" title="类初始化函数init"></a>类初始化函数init</h2><p>可以注意到上面的例子, 我们在子类中编写 <code>__init__</code>时</p>
<p>会有 <code>super().__init__()</code></p>
<p>这个实际上是编码工具自动带出来的, 为什么呢? 以为它确实需要.</p>
<p>文字说起来可能不太直观, 我们来看代码.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, parentName</span>) -&gt; <span class="hljs-literal">None</span>:<br>        self.parentName = parentName<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">showParentName</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(self.parentName) <br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, childName</span>) -&gt; <span class="hljs-literal">None</span>:<br>        self.childName = childName<br><br>child = Child(<span class="hljs-string">&#x27;muzhou&#x27;</span>)<br><br>child.showParentName()  <span class="hljs-comment"># 调用的父类的方法 报错啦</span><br></code></pre></td></tr></table></figure>

<p>这个时候, <code>showParentName</code> 这个函数, 调用的是 <code>self.parentName</code></p>
<p>这个 <code>parentName</code> 在子类中没有定义, 只有在父类中通过 <strong><strong>init</strong></strong> 来给予</p>
<p>所以我们在子类的 <code>__init__</code> 中还需要单独调用 <code>super().__init__()</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, parentName</span>) -&gt; <span class="hljs-literal">None</span>:<br>        self.parentName = parentName<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">showParentName</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(self.parentName) <br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, parentName</span>) -&gt; <span class="hljs-literal">None</span>:<br>        <span class="hljs-built_in">super</span>().__init__(parentName)<br><br>child = Child(<span class="hljs-string">&#x27;muzhou&#x27;</span>)<br><br>child.showParentName()  <span class="hljs-comment"># 调用的父类的方法</span><br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, parentName</span>) -&gt; <span class="hljs-literal">None</span>:<br>        self.parentName = parentName<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">showParentName</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(self.parentName) <br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(<span class="hljs-title class_ inherited__">Parent</span>):  <span class="hljs-comment"># 继承方式就是在定义类的时候，在括号里写上需要继承的类</span><br>    <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, parentName, childName</span>) -&gt; <span class="hljs-literal">None</span>:<br>        <span class="hljs-built_in">super</span>().__init__(parentName)<br>        self.childName = childName<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">showMyName</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(self.childName)<br><br><br>child = Child(<span class="hljs-string">&#x27;muzhouParent&#x27;</span>, <span class="hljs-string">&#x27;muzhouChild&#x27;</span>)  <span class="hljs-comment"># 因为child的 __init__ 用到了两个参数</span><br><br>child.showParentName()  <span class="hljs-comment"># 调用的父类的方法</span><br>child.showMyName()  <span class="hljs-comment"># 调用的子类的方法</span><br></code></pre></td></tr></table></figure>


<h2 id="继承可以迭代"><a href="#继承可以迭代" class="headerlink" title="继承可以迭代"></a>继承可以迭代</h2><p>就是子类继承父类, 孙类继承子类</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Grand</span>():<br>    ...<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>(<span class="hljs-title class_ inherited__">Grand</span>):<br>    ...<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Chlid</span>(<span class="hljs-title class_ inherited__">Parent</span>):<br>    ...<br></code></pre></td></tr></table></figure>


<h2 id="继承可以怎么玩"><a href="#继承可以怎么玩" class="headerlink" title="继承可以怎么玩"></a>继承可以怎么玩</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">BWM</span>():<br>    brand = <span class="hljs-string">&quot;BMW&quot;</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">func</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;宝马都有的功能&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">face</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;宝马都有的大鼻孔&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">BWM5</span>(<span class="hljs-title class_ inherited__">BWM</span>):<br>    height = <span class="hljs-number">1400</span><br>    width = <span class="hljs-number">4000</span><br>    price = <span class="hljs-string">&#x27;20w&#x27;</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, color</span>) -&gt; <span class="hljs-literal">None</span>:<br>        <span class="hljs-built_in">super</span>().__init__()<br>        self.color = color<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">func</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">super</span>().func()<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;BMW5特有的功能&quot;</span>)<br><br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">BWM7</span>(<span class="hljs-title class_ inherited__">BWM</span>):<br>    height = <span class="hljs-number">2000</span><br>    width = <span class="hljs-number">6000</span><br>    price = <span class="hljs-string">&#x27;30w&#x27;</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, color</span>) -&gt; <span class="hljs-literal">None</span>:<br>        <span class="hljs-built_in">super</span>().__init__()<br>        self.color = color<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">func</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">super</span>().func()<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;BMW7特有的功能&quot;</span>)<br><br><br>bmw5 = BWM5(<span class="hljs-string">&#x27;blue&#x27;</span>)<br>bmw7 = BWM7(<span class="hljs-string">&#x27;blue&#x27;</span>)<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;我的牌子 <span class="hljs-subst">&#123;bmw5.brand&#125;</span>, 我的宽高 height: <span class="hljs-subst">&#123;bmw5.height&#125;</span> width: <span class="hljs-subst">&#123;bmw5.width&#125;</span>, 单价: <span class="hljs-subst">&#123;bmw5.price&#125;</span>&quot;</span>)<br>bmw5.func()<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;我的牌子 <span class="hljs-subst">&#123;bmw7.brand&#125;</span>, 我的宽高 height: <span class="hljs-subst">&#123;bmw7.height&#125;</span> width: <span class="hljs-subst">&#123;bmw7.width&#125;</span>, 单价: <span class="hljs-subst">&#123;bmw7.price&#125;</span>&quot;</span>)<br>bmw7.func()<br><br>bmw5.face()<br>bmw7.face()<br></code></pre></td></tr></table></figure>

<p>总结就是:</p>
<ul>
<li>封装一个基类, 这个基类具备基本且通用的信息, 以及一些功能</li>
<li>封装一个子类, 这个子类在父类的基础上进行拓展/重写</li>
</ul>
<p>总之, 如何设计程序, 主要在于编码者的经验, 只要最后能达到想要的效果, 任何手段都是正确的, 只要确认自己每一次封装都比上一次更加得心应手且便于维护即可.</p>
<h2 id="多继承"><a href="#多继承" class="headerlink" title="多继承"></a>多继承</h2><p>之前展示的都是 <strong>单继承</strong></p>
<p>单实际上, 还可以进行多继承</p>
<p>顾名思义, 就是一个子类可以有两个 <strong>爸爸</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Animal</span>():  <span class="hljs-comment"># 动物</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">eat</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;动物都会吃饭&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">WildAnimal</span>():  <span class="hljs-comment"># 野生动物</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">hunt</span>(): <br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;野生动物会捕猎&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Pet</span>():  <span class="hljs-comment"># 宠物</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">play</span>():<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;和主人一块玩&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">哈士奇</span>(Animal, Pet):<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">info</span>():<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;不太聪明的样子&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Wolf</span>(Animal, WildAnimal):<br>    ...<br><br>哈狗 = 哈士奇()<br><br>哈狗.info()<br>哈狗.eat()<br>哈狗.play()<br></code></pre></td></tr></table></figure>

<h2 id="多继承引用顺序"><a href="#多继承引用顺序" class="headerlink" title="多继承引用顺序"></a>多继承引用顺序</h2><p>既然类可以多继承, 那么肯定会存在继承查找顺序问题</p>
<p>即相同的属性/方法, 如果多继承, 那么最先引用的是哪一个类</p>
<p>这里就要涉及到两个类别:</p>
<ul>
<li>经典类</li>
<li>新式类</li>
</ul>
<p><strong>经典类</strong></p>
<p>python2版本才会存在的类, 即不继承 <code>object</code>的类</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Grand</span>():  <span class="hljs-comment"># 经典类</span><br>    ...<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>(<span class="hljs-title class_ inherited__">Grand</span>): <span class="hljs-comment"># 经典类</span><br>    ...<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Grand</span>(<span class="hljs-title class_ inherited__">object</span>):  <span class="hljs-comment"># 新式类</span><br>    ...<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent</span>(<span class="hljs-title class_ inherited__">Grand</span>): <span class="hljs-comment"># 新式类</span><br>    ...<br></code></pre></td></tr></table></figure>

<p>可以这么理解, python2中, 只要最终的父类不继承 <code>object</code> 都是经典类</p>
<p><strong>新式类</strong></p>
<p>在python3中, 没有 <strong>经典类</strong>, 只会存在 <strong>新式类</strong></p>
<p>因为python3的中类, 以及默认都是继承 <code>object</code></p>
<p>根据类别不同, 有两种查找方式:</p>
<ul>
<li>经典类: 深度优先</li>
<li>新式类: 广度优先</li>
</ul>
<p>通过以下相同的代码来解析</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Grand</span>():<br>    ...<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">info</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Grand&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent1</span>(<span class="hljs-title class_ inherited__">Grand</span>):<br>    ...<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">info</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Parent1&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Parent2</span>(<span class="hljs-title class_ inherited__">Grand</span>):<br>    <span class="hljs-comment"># ...</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">info</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Parent2&quot;</span>)<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Child</span>(Parent1, Parent2):<br>    ...<br><br>child = Child()<br>child.info()<br><br><span class="hljs-built_in">print</span>(Child.__mro__)<br></code></pre></td></tr></table></figure>

<p>我们可以直接通过 <code>__mro__</code> 来查看顺序</p>
<p><strong>深度优先</strong></p>
<p>查找顺序: Child -&gt; Parent1 -&gt; Grand -&gt; Parent2</p>
<p>简单来说, 就是<strong>一条路走到黑</strong>, 先走的是<strong>最近</strong>的类, 也就是继承的最左边的类</p>
<p>通过最左边的类, 一直往上找, 找到它的最终父类为为止</p>
<p>如果找到最终的父类都没有找到, 才会从第二个继承的类开始往上找.</p>
<p><em><strong>现在都是用的python3, 目前基本是看不到深度优先了, 有兴趣的可以单独装个python2来看看</strong></em></p>
<p><strong>广度优先</strong></p>
<p>查找顺序: Child -&gt; Parent1 -&gt; Parent2 -&gt; Grand</p>
<p>简单来说, 就是从左往右找, 先找同级, 如果同级没有, 就再找父类.</p>
<p>定义同级的方式是需要两个类都继承 <strong>同一个</strong> 父类.</p>
<h1 id="多态"><a href="#多态" class="headerlink" title="多态"></a>多态</h1><p>实际上多态就是我们在上面说过的 <strong>重写方法/属性</strong></p>
<p>就是在子类中将父类中相同函数进行重写逻辑</p>
<p>你可以在其中进行 功能拓展/覆盖</p>
<p>多态存在的意义, 就是让面向对象 <strong>更加灵活</strong></p>
<p>并不仅仅局限于 <strong>继承父类</strong> </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Animail</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">eat</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;在吃东西......&quot;</span>)<br><span class="hljs-keyword">class</span>  <span class="hljs-title class_">Cat</span>(<span class="hljs-title class_ inherited__">Animail</span>):<br>      <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">eat</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-comment"># 执行父类的原来的逻辑代码  父类名.方法名(self)</span><br>        <span class="hljs-built_in">super</span>().eat()   <span class="hljs-comment"># Animail.eat(self)</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;吃的是一条小鱼&quot;</span>)<br>      <br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">running</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;跑步&#x27;</span>)<br></code></pre></td></tr></table></figure>


<h1 id="反射"><a href="#反射" class="headerlink" title="反射"></a>反射</h1><p>可以发现, 我们调用对象的属性和方法</p>
<p>看起来很像是 <strong>字典</strong> 的调用方式</p>
<p>不同的是字典是 <code>dict[&#39;xx&#39;]</code></p>
<p>但字典的这种方式显然更加灵活, 因为 <code>key</code> 值可以填入一个变量来查找, 比如:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python">d = &#123;<span class="hljs-string">&#x27;name&#x27;</span>: <span class="hljs-string">&#x27;muzhou&#x27;</span>&#125;<br>nameKey = <span class="hljs-string">&#x27;name&#x27;</span><br><span class="hljs-built_in">print</span>(d[name])<br></code></pre></td></tr></table></figure>

<p>但是对象都是 <code>d.xx</code>, 按照目前我们所学的知识, 无法通过 <strong>变量填入</strong> 的形式来获取/增加/删除某个值</p>
<p>所以我们需要学习 <strong>反射</strong></p>
<p><strong>反射就是通过字符串的形式去对象（模块）中操作（查找/获取/删除/添加）成员，一种基于字符串的事件驱动</strong></p>
<p>反射有三个函数:</p>
<ul>
<li>getattr, 通过字符串获取对象的属性/方法</li>
<li>setattr, 通过字符串给对象的属性/方法赋值</li>
<li>hasattr, 通过字符串来判断对象是否拥有某个属性/方法</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestObj</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, name, age</span>):<br>        self.name = name<br>        self.age = age<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;执行test方法&quot;</span>)<br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">a</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;类外部方法&quot;</span>)<br><br>xiaoyu = TestObj(<span class="hljs-string">&#x27;小宇&#x27;</span>, <span class="hljs-number">18</span>)<br>  <br><span class="hljs-built_in">print</span>(<span class="hljs-built_in">getattr</span>(xiaoyu, <span class="hljs-string">&quot;name&quot;</span>))   <span class="hljs-comment"># 获取对象属性/对象方法</span><br><br>test = <span class="hljs-built_in">getattr</span>(xiaoyu, <span class="hljs-string">&quot;test&quot;</span>)   <span class="hljs-comment"># 获取对象方法</span><br>test()<br><br><span class="hljs-built_in">print</span>(<span class="hljs-built_in">hasattr</span>(xiaoyu, <span class="hljs-string">&quot;adress&quot;</span>))   <span class="hljs-comment"># 判断对象是否有对应的属性及方法,返回True或Fals</span><br><br><span class="hljs-built_in">setattr</span>(xiaoyu, <span class="hljs-string">&quot;name&quot;</span>, <span class="hljs-string">&quot;winnie&quot;</span>) <span class="hljs-comment"># 修改属性的值</span><br><span class="hljs-built_in">setattr</span>(xiaoyu, <span class="hljs-string">&quot;test1&quot;</span>, a)   <span class="hljs-comment"># 修改方法</span><br><br><span class="hljs-built_in">print</span>(xiaoyu.name)<br>test1 = <span class="hljs-built_in">getattr</span>(xiaoyu, <span class="hljs-string">&quot;test1&quot;</span>)   <span class="hljs-comment"># 获取对象方法</span><br>test1()<br><br><span class="hljs-built_in">print</span>(xiaoyu.name)<br><span class="hljs-built_in">delattr</span>(xiaoyu, <span class="hljs-string">&quot;name&quot;</span>)  <span class="hljs-comment"># 删除指定的属性</span><br><span class="hljs-built_in">print</span>(xiaoyu.name)  <span class="hljs-comment"># 报错</span><br><br></code></pre></td></tr></table></figure>


                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/python/" class="category-chain-item">python</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/python/Python%E5%9F%BA%E7%A1%80/" class="category-chain-item">Python基础</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/Python%E5%9F%BA%E7%A1%80/">#Python基础</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>python面向对象（下）</div>
      <div>https://walker_kwu.gitee.io/my-blog/2023/03/11/python/base/python面向对象（下）/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年3月11日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2023/03/18/python/base/python%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%E5%8F%8A%E6%96%87%E4%BB%B6%E5%A4%84%E7%90%86/" title="python异常处理及文件处理">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">python异常处理及文件处理</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2023/03/11/python/base/python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%EF%BC%88%E4%B8%8A%EF%BC%89/" title="python面向对象（上）">
                        <span class="hidden-mobile">python面向对象（上）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
